package com.jt.service;

import com.jt.vo.ImageVO;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class FileServiceImpl implements FileService {

    //定义文件的根目录
    private String rootDir = "D:/project3/images";
    //linux部署需要跟换路径
//    private String rootDir = "/usr/local/src/images";

    //定义图片服务器网址
    private String rootURL = "http://image.jt.com";
    /**
     * 思路：
     *    1.校验文件是否为图片   校验图片类型
     *    2.防止文件为恶意文件   木马.exe.jpg
     *    3.分目录存储         按照时间维度划分
     *    4.防止文件重名        UUID
     * @param file
     * @return
     */
    @Override
    public ImageVO upload(MultipartFile file) {
        //1.校验文件是否为图片
        String fileName = file.getOriginalFilename().toLowerCase();
        if(!fileName.matches("^.+\\.(jpg|png|gif)$")){
            return null;
        }

        //2.通过校验宽度和高度判断是否为图片 bufferedImage图片包装对象
        try {
            BufferedImage read = ImageIO.read(file.getInputStream());
            int height = read.getHeight();
            int width = read.getWidth();
            if(width == 0||height ==0){
                return null;
            }
            //3.实现分目录的存储                            //年/月/日 有固定语法(大小写)，但是这里是路径
            String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
            String fileDir = rootDir + datePath;
            File DirFile = new File(fileDir);
            if (!DirFile.exists()){
                DirFile.mkdirs(); //mkdirs   创建多级目录
            }

            //4.动态生成UUID
            String UUID = java.util.UUID.randomUUID().toString();
            int index = fileName.lastIndexOf(".");
            String fileType = fileName.substring(index);
            fileName = UUID+fileType;

            //5.实现文件的上传   准备文件的全路径
            String path = fileDir + fileName;
            file.transferTo(new File(path));

            //6.准备ImageVO数据返回
            //封装VO对象对象
            String virtualPath = datePath + fileName;
            //String urlPath = "https://img14.360buyimg.com/n5/s54x54_jfs/t1/204372/5/3956/58749/612e0eadE1699635c/60b10d06337d226d.jpg";
            String urlPath = rootURL + virtualPath;
            System.out.println(urlPath);
            ImageVO imageVO = new ImageVO(virtualPath, urlPath, fileName);
            return imageVO;
        } catch (IOException e) {
            //一般条件下为了不影响代码结构,将检查异常,转化为运行时异常
            e.printStackTrace();
            throw new RuntimeException(e);

        }

    }

    //删除文件需要文件的全路径
    @Override
    public void deleteFile(String virtualPath) {
        String localPath = rootDir + virtualPath;
        File file = new File(localPath);
        if (file.exists()){//如果文件存在，则删除
            file.delete();
        }
    }
}
